///新版本 我的
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/NewMine/AccountViewModel.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/zjTopBar.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/textUtils.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../base/basewidget/view/BaseWidget.dart';

const double space = 15;

class MyNewView extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    return MyViewState();
  }
}

class MyViewState extends BaseState<AccountViewModel, MyNewView> {
  Map _data;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    Future.delayed(Duration.zero, () {
      _getData();
      _tenantData();
    });
  }

  _getData() async {
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      return ToastUtils.showToast("请检查手机网络设置");
    }
    viewModel.getUserInfo();
    viewModel.getUserInfoDataStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          _data = event['data'];
        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  String _tenantName = '';
  _tenantData() {
    viewModel.tenantApprove();
    viewModel.gettenantDataStream().listen((event) {
      if (event['code'] == "0") {
        setState(() {
          _tenantName = event['data']['tenantName'];
        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  @override
  Widget initWidget() {
    return Container(
      decoration: BoxDecoration(
          color: Color(0x00f6f7f8),
          image: DecorationImage(
              fit: BoxFit.fitWidth,
              image: AssetImage(
                "img/my_bg.png",
              ))),
      child: Scaffold(
        backgroundColor: Color(0x00f6f7f8),
        appBar: ZJTopBar(
            backgroundColor: Color(0x00f6f7f8),
            elevation: 0,
            title: '我的',
            rightButtonColor: SQColor.black_333333,
            rightButtonIcon: Icons.headset,
            onRightButtonIconClick: () {
              _call('400-071-1996');
            }).create(),
        body: _bodyView(),
      ),
    );
  }

  _call(String phone) async {
    String result = await PerUtils.checkPermission(context, [Permission.phone]);
    if (result == "1") {
      if (TextUtils.getStr(phone) != "") launch("tel:$phone");
    }
  }

  _bodyView() {
    bool _isLogin1 = isEmpty(UserInfoUtils.getUserToken());

    return Container(
      // height: ScreenUtil.getScreenH(context),
      child: Column(
        children: [
          _topView(),
          _listContent(context),
          // Expanded(child: _listContent(context)),
          Expanded(
            child: Container(),
          ),
          _isLogin1 ? Container() : _bottomBtnView()
        ],
      ),
    );
  }

  _topView() {
    bool _isLogin = isEmpty(UserInfoUtils.getUserToken());

    return Container(
      padding: EdgeInsets.only(left: Dimens.dimens16, bottom: Dimens.dimens16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          InkWell(
            onTap: () => {},
            child: Container(
              height: 60,
              width: 60,
              child: ClipOval(
                  child:
                      // !_isLogin && !EmptyUtils.isForEmpty(_data) && !EmptyUtils.isForEmpty(_data['avatarPath']) ?
                      Image.asset(
                'img/wd_mr.png',
                height: Dimens.dimens60,
                width: Dimens.dimens60,
                fit: BoxFit.fill,
              )
                  // : ImageWidget(
                  //     fileName: _data['avatarPath'],
                  //     width: Dimens.dimens60,
                  //     height: Dimens.dimens60,
                  //     boxFit: BoxFit.fill),
                  ),
            ),
          ),
          Expanded(
            child: Container(
              padding: EdgeInsets.only(left: Dimens.dimens6),
              height: 80,
              alignment: Alignment.centerLeft,
              child: InkWell(
                onTap: () {
                  if (_isLogin) {
                    Navigator.pushNamed(context, "/LoginPageView");
                  }
                },
                child: new Container(
                  // alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      JText(
                        _data == null
                            ? '登录/注册'
                            : '${StringUtils.getStr(_data['nickname'])}',
                        color: SQColor.black_333333,
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                      SizedBox(
                        height: Dimens.dimens4,
                      ),
                      JText(
                        _isLogin ? "点击登录注册" : _tenantName,
                        color:
                            _isLogin ? SQColor.black_999999 : Color(0xff3264F5),
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
          _isLogin
              ? Container()
              : Container(
                  child: InkWell(
                    onTap: () {
                      Navigator.pushNamed(context, "/ChangeSFView")
                          .then((value) {
                        _getData();
                        _tenantData();
                      });
                    },
                    child: Card(
                      elevation: 2,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(
                              Radius.circular(Dimens.dimens16))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            "img/change_sf.png",
                            width: 14,
                            height: 14,
                          ),
                          JText(
                            ' 切换身份',
                            color: Color(0xff333333),
                            fontSize: 13,
                          )
                        ],
                      ),
                    ),
                  ),
                  margin: EdgeInsets.only(right: 15, left: 5),
                  width: 100,
                  height: 36,
                ),
        ],
      ),
    );
  }

  _listContent(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: Dimens.dimens14, right: Dimens.dimens14),
      decoration: BoxDecoration(
        color: SQColor.white,
        borderRadius: BorderRadius.all(Radius.circular(4.0)),
      ),
      child: Column(
        children: [
          _itemcontent("账号与安全"),
          _itemcontent("关于我们"),
        ],
      ),
    );
  }

  _itemcontent(String content) {
    return InkWell(
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Container(
                  height: 59,
                  padding: EdgeInsets.only(left: Dimens.dimens16),
                  child: Row(
                    children: [
                      Image.asset(
                        content == "关于我们"
                            ? "img/aboutus.png"
                            : "img/account_safe.png",
                        width: Dimens.dimens24,
                        height: Dimens.dimens24,
                      ),
                      SizedBox(
                        width: Dimens.dimens16,
                      ),
                      JText(
                        content,
                        color: SQColor.black_333333,
                        fontSize: 14,
                        fontWeight: FontWeight.w400,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Container(
                padding: EdgeInsets.only(right: Dimens.dimens18),
                child: Center(
                  child: Icon(
                    Icons.arrow_forward_ios_outlined,
                    size: Dimens.dimens15,
                    color: SQColor.black_999999,
                  ),
                )),
          ],
        ),
        height: 59,
      ),
      onTap: () {
        bool _isLogin = isEmpty(UserInfoUtils.getUserToken());
        if (_isLogin) {
          Navigator.pushNamed(context, "/LoginPageView");
          return;
        }
        if (content == "关于我们") {
          Navigator.pushNamed(context, "/AboutUsPageView");
        } else {
          Navigator.pushNamed(context, "/AccountDetailView");
        }
      },
    );
  }

  _bottomBtnView() {
    return InkWell(
      onTap: () {
        _loginOut();
      },
      child: SafeArea(
        child: Container(
          margin: EdgeInsets.only(left: 15, right: 15, bottom: 15),
          height: 45,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: SQColor.white,
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                color: SQColor.blue_026FFF,
                width: 1,
              )),
          child: JText('退出登录', color: SQColor.blue_026FFF),
        ),
      ),
    );
  }

  _loginOut() {
    viewModel.loginOut();
    viewModel.loginOutStream().listen((event) {
      if (event['code'] == '0') {
        UserInfoUtils.setUserToken('');
        Navigator.pushNamedAndRemoveUntil(
            context, "/LoginPageView", (route) => false);
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }
}
